package com.alipay.app.groupmeal.standard.base;

import android.accounts.NetworkErrorException;
import android.text.TextUtils;

import com.alipay.app.groupmeal.standard.constant.BaseConstant;
import com.alipay.app.groupmeal.standard.http.bean.resp.BaseResp;
import com.blankj.utilcode.util.NetworkUtils;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.observers.ResourceObserver;

/**
 * 事件观察者 基类
 * 做一些统一处理
 */
public abstract class BaseObserver<T> extends ResourceObserver<BaseResp<T>> {

    private AbstractView mView;

    public BaseObserver(AbstractView view) {
        this.mView = view;
    }

    @Override
    protected void onStart() {
        super.onStart();
        //请求前置判断
        if (!NetworkUtils.isConnected()) {
            onError(new NetworkErrorException("无网络，请检查你的网络设置"));
            return;
        }
    }

    @Override
    public void onNext(@NonNull BaseResp<T> response) {
        if (TextUtils.equals(response.code, BaseConstant.SERVER_SUCCESS_CODE))
            doNext(response.data);
        else {
            //失败回调 内部做一些异常处理
            doError(response.code, TextUtils.isEmpty(response.sub_msg) ? response.msg : response.sub_msg);
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        doError("-1", e.getMessage());
    }

    @Override
    public void onComplete() {
    }

    public abstract void doNext(T t);

    public abstract void doError(String code, String msg);

}
